<template>
  <div>
      <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
        <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="adduserinfo">添加用户</el-button>
        </el-col>
        </el-row>
        <!-- 角色列表 -->
        <el-table :data="roleslist" border stripe >
            <!-- 角色信息展开 -->
            <el-table-column type="expand">
                 <template slot-scope="scope">
                  <el-row class="firstrow" v-for="(item1,index) in scope.row.children" :key="item1.id" :class="['borderbottom',index===0 ? 'bordertop' : '']">   
                    <!-- 一级权限 -->
                    <el-col :span="5">
                        <el-tag @close="closetag(scope.row,item1)" closable>{{item1.authName}}<i class="el-icon-caret-right"></i></el-tag>
                    </el-col>
                    <!-- 二三级权限 -->
                    <el-col :span="19">
                        <el-row :span="6" v-for="(item2,index) in item1.children" :key="item2.id"
                         :class="['borderbottom',index===0 ? '' : 'bordertop']" class="firstrow">
                           <!-- 二级 -->
                           <el-col :span="6">
                              <el-tag type="success" @close="closetag(scope.row,item2)" closable>{{item2.authName}}<i class="el-icon-caret-right"></i></el-tag>
                           </el-col>
                           <!-- 三级 -->
                           <el-col  :span="18">
                                <el-tag v-for="(item3) in item2.children" :key="item3.id" closable @close="closetag(scope.row,item3)"
                                 type="warning" class="thirdchildren">{{item3.authName}}</el-tag>
                           </el-col>
                        </el-row>
                    </el-col>
                         
                  </el-row>
                 </template>
            </el-table-column>
           <el-table-column type="index" label="#"></el-table-column>
           <el-table-column prop="roleName" label="角色名称"></el-table-column>
           <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
           <el-table-column label="操作">
               <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="edituserinfo(scope.row)" icon="el-icon-edit" plain>编辑</el-button>
                  <el-button type="success" size="mini" @click="setpowertouser(scope.row)" icon="el-icon-star-off" plain>分配</el-button>
                  <el-button type="danger" size="mini" @click="deleteuserinfo(scope.row)" icon="el-icon-delete" plain>删除</el-button>
               </template>
           </el-table-column>
        </el-table>

        <!-- 添加角色表单弹出层 -->
        <el-dialog title="添加用户" :visible.sync="adduserinfofrom"
                  width="50%" :before-close="handleClose">
            <!-- 添加角色主题区域 -->
            <el-form :model="adduserform" status-icon :rules="adduserformrules"
             ref="adduserform" label-width="100px">
               <el-form-item label="角色名" prop="roleName">
                 <el-input v-model="adduserform.roleName"></el-input>
               </el-form-item>
               <el-form-item label="角色描述" prop="roleDesc">
                 <el-input v-model="adduserform.roleDesc"></el-input>
               </el-form-item>
          </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closedadduserinfo">取 消</el-button>
              <el-button type="primary" @click="submitadduserinfo">确 定</el-button>
            </span>
       </el-dialog>

       <!-- 编辑角色信息表单弹出层 -->
      <el-dialog title="修改角色信息" :visible.sync="edituserinfoform"
         width="50%" :before-close="handleClose">
          <!-- 编辑用户表单区域 -->
          <el-form :model="edituserform" status-icon :rules="adduserformrules"
           ref="edituserformrule" label-width="100px">
              <el-form-item label="角色名" prop="roleName">
                 <el-input v-model="edituserform.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="edituserform.roleDesc"></el-input>
             </el-form-item>
        </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closededituserinfo">取 消</el-button>
            <el-button type="primary" @click="submitedituserinfo">确 定</el-button>
          </span>
      </el-dialog>
      
      <!-- 分配权限弹出层 -->
      <el-dialog title="分配权限" :visible.sync="setrightfrom"
            width="50%" :before-close="handleClose">
            <!-- <span>这是一段信息</span> -->
            <el-tree :data="righttreedata" :props="showtreedata" show-checkbox node-key="id"
            :default-expanded-keys="defaultcheckkey" ref="righttreeref" :default-checked-keys="defaultcheckkey">
             </el-tree>
            <template slot="footer">
              <el-button @click="removesetpower">取 消</el-button>
              <el-button type="primary" @click="certainsetpower">确 定</el-button>
            </template>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
export default {
   name:'Roles',
   data(){
       return{
          roleslist:[],
        //   添加角色表单
          adduserinfofrom:false,
        //   编辑角色表单
          edituserinfoform:false,
        //   分配权限弹出层
          setrightfrom:false,
          adduserform:{
              roleName:'',
              roleDesc:''
          },
          adduserformrules:{
              roleName:[
                { required: true, message: '请输入角色名', trigger: 'blur' },
                {min: 2,max: 10,message: '角色名的长度在2～10个字',trigger: 'blur'}
              ],
              roleDesc:[
                { required: true, message: '请输入角色描述', trigger: 'blur' },
                {min: 2,max: 10,message: '角色描述长度在2～10个字',trigger: 'blur'}
              ]
          },
        //   编辑角色信息
          edituserform:{
              roleName:'',
              roleDesc:''
          },
        //   权限树数据
          righttreedata:[],
        //   显示权限树props
          showtreedata:{
              label:'authName',
              children:'children'
          },
        //   默认选中的tree节点,存放ID
          defaultcheckkey:[],
        //   存放角色唯一ID
        rightID:''
       }
   },
   created(){
       this.getrolelist()
   },
   methods:{
       async getrolelist(){
           const {data:res}=await this.$http.get('roles')
           if(res.meta.status!==200){return this.$message.error('获取角色列表失败')}
           this.$message.success(res.meta.msg)
           this.roleslist=res.data
       },
    //    点击添加用户
       adduserinfo(){
           this.adduserinfofrom=true
       },
           //   点击编辑角色信息
              async edituserinfo(row){
           this.edituserinfoform=true
           const {data:res}=await this.$http.get(`roles/${row.id}`)
           this.edituserform=res.data
              },
           //    点击删除角色信息
               deleteuserinfo(row){
            this.$confirm('确认关闭？')
             .then(async ()=> { 
                 const {data:res}=await this.$http.delete(`roles/${row.id}`)
                 if(res.meta.status!=200){
                 return this.$message.error('删除角色失败')
                   }
                 this.$message.success('删除角色成功')
                 this.getrolelist()
              })
             .catch(()=> {});

               },
            // 点击分配权限信息
             async setpowertouser(row){
                 const {data:res}=await this.$http.get('rights/tree')
                 if(res.meta.status!==200){return this.$message('获取权限树失败')}
                 this.righttreedata=res.data
                 this.rightID=row.id
                //  循环递归得出已选中ID
                 this.getdefaultcheckroleid(row,this.defaultcheckkey)
                 this.$message.success(res.meta.msg)
                //  console.log(this.defaultcheckkey);
                 this.setrightfrom=true
                 
             },
       // 点击x 关闭前的回调，会暂停 Dialog 的关闭
      handleClose(done){
         this.$confirm('确认关闭？')
           .then(_ => { done() })
           .catch(_ => {});
    },
    // 取消添加用户表单
    closedadduserinfo(){
        this.$refs.adduserform.resetFields()
        this.adduserinfofrom=false
    },
    // 确定添加角色信息
    submitadduserinfo(){
        this.$refs.adduserform.validate(async (valid)=>{
            if(!valid){return this.$message.error('验证未通过')}
            const {data:res}=await this.$http.post('roles',this.adduserform)
            if(res.meta.status!==201){return this.$message.error('添加失败')}
            this.$message.success(res.meta.msg)
            this.getrolelist()
        })
        this.adduserinfofrom=false
        this.$refs.adduserform.resetFields()
    },
    // 取消编辑角色信息对话框
    closededituserinfo(){
        this.edituserinfoform=false
        this.$refs.edituserformrule.resetFields()
    },
    // 确定提交编辑角色信息
    submitedituserinfo(){
        this.$refs.edituserformrule.validate(async (valid)=>{
            if(!valid){return this.$message.error('编辑失败')}
            const {data:res}=await this.$http.put(`roles/${this.edituserform.roleId}`,this.edituserform)
            this.$message.success('编辑成功')
            
        })
        this.getrolelist()
        this.edituserinfoform=false
        this.$refs.edituserformrule.resetFields()
    },
    // 关闭分配权限弹出层
    removesetpower(){
        this.defaultcheckkey=[]
        this.setrightfrom=false
    },
    // 确定修改权限分配
    async certainsetpower(){
        // 得到全选或半选状态key
        const idstring=[
            ...this.$refs.righttreeref.getHalfCheckedKeys(),
            ...this.$refs.righttreeref.getCheckedKeys()
        ]
        const idstrings= idstring.join(',')
        const{data:res} =await this.$http.post(`roles/${this.rightID}/rights`,
                        { rids:idstrings })
        if(res.meta.status!==200){return this.$message('修改权限失败')}
        this.righttreedata=res.data
        console.log(res);
        this.$message.success(res.meta.msg)
        this.defaultcheckkey=[]
        this.getrolelist()
        this.setrightfrom=false
    },
    // 点击关闭tag标签
    closetag(roleid,rightid){

        this.$confirm('确认取消？')
           .then(async () => { 
               const {data:res}=await this.$http.delete(`roles/${roleid.id}/rights/${rightid.id}`)
               if(res.meta.status!=200) {return this.$message('取消权限失败')}
               this.$message.success(res.meta.msg)
            //    this.getrolelist()
               roleid.children=res.data
            })
           .catch( () => {});
    },
    // 循环递归函数找到已有所有权限ID
    getdefaultcheckroleid(node,array){
        //  循环递归得到当前角色id
        if(!node.children){
            return array.push(node.id)
        }
        node.children.forEach(item => {
            this.getdefaultcheckroleid(item,array)
        });
    }
   }
}
</script>

<style lang="less" scoped>
   .el-card{
       margin-top: 20px;
   }
   .el-row{
       margin-bottom: 10px;
   }
   .bordertop{
       border-top: 1px solid seagreen;
   }
   .borderbottom{
       border-bottom: 1px solid seagreen;
   }
   .firstrow{
       display: flex;
    //    justify-content: center;
       align-items: center;
       flex-wrap: nowrap;
   }
   .thirdchildren{
       margin: 2px 4px;
   } 
</style>